package com.tl.web05.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.tl.web05.config.Config;
import com.tl.web05.constant.ResponseResult;
import com.tl.web05.dao.UserDao;
import com.tl.web05.model.entity.User;
import com.tl.web05.service.UserService;
import com.tl.web05.utils.JsonParamUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "AjaxModifyServlet", urlPatterns = "/ajax_modify")
public class ModifyServlet extends HttpServlet {
    private UserService userService = new UserService(new UserDao());

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //配置响应编码
//            request.setCharacterEncoding(Config.REQ_ChARSET);
            response.setContentType(Config.RESP_JSON_CONTENT_TYPE);
            //获取参数
            JSONObject jsonParam = JsonParamUtil.getJsonParam(request);
            String username = jsonParam.getString("username");
            String password = jsonParam.getString("password");
            String nickname = jsonParam.getString("nickname");
            String age = jsonParam.getString("age");
            String birthday = jsonParam.getString("birthday");
            //获取输出
            PrintWriter out = response.getWriter();
            //获取全局域
//            ServletContext application = request.getServletContext();

            //编辑的方法
//            ResponseResult result = null;
//            try {
//                User user = new User(username, password, nickname, Integer.parseInt(age), DateUtil.parase(birthday, DateUtil.DATEFORMATDAY));
//                result = userService.modify(application, user);
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
            //数据库编辑
            ResponseResult result = userService.modifyUser(new User(username, password, nickname, Integer.parseInt(age), DateUtil.parse(birthday, "yyyy-MM-dd")));
            //向页面输出响应
            out.print(JSONObject.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }
}
